<template>
    <section class="page-container-list">
        <a-tabs v-model:activeKey="activeKey">
            <a-tab-pane key="1" tab="收支明细">
                <div class="page-search-form mb-24">
                    <a-range-picker v-model:value="transactionForm.date" :show-time="{ format: 'HH:mm' }"
                        format="YYYY-MM-DD HH:mm" class="mr-24" @change="queryTransactionList" />
                    <a-select ref="select" v-model:value="transactionForm.tradeType" placeholder="全部交易类型" allowClear
                        @change="queryTransactionList">
                        <a-select-option value="线上充值">线上充值</a-select-option>
                        <a-select-option value="线下充值">线下充值</a-select-option>
                        <a-select-option value="实例创建">实例创建</a-select-option>
                        <a-select-option value="实例续租">实例续租</a-select-option>
                        <a-select-option value="实例自动续费">实例自动续费</a-select-option>
                        <a-select-option value="订单结算">订单结算</a-select-option>
                        <a-select-option value="实例存储-开机">实例存储-开机</a-select-option>
                        <a-select-option value="实例存储-关机">实例存储-关机</a-select-option>
                        <a-select-option value="网盘存储">网盘存储</a-select-option>
                        <a-select-option value="镜像存储">镜像存储</a-select-option>
                        <a-select-option value="账户提现">账户提现</a-select-option>
                        <a-select-option value="账户提现退回">账户提现退回</a-select-option>
                        <a-select-option value="转按量退款">转按量退款</a-select-option>
                    </a-select>
                </div>

                <div class="page-content">
                    <a-table :dataSource="transactionList" :pagination="false" :loading="transactionListLoading">
                        <a-table-column key="createdAt" data-index="createdAt" title="交易时间" />
                        <a-table-column key="subject" data-index="subject" title="交易类型" />
                        <a-table-column key="amount" data-index="amount" title="交易金额(元)">
                            <template #default="{ record }">
                                {{ record.event == '1' ? '+' : record.event == '2' ? '-' : '' }} {{ record.amount }}
                            </template>
                        </a-table-column>
                        <a-table-column key="afterBalance" data-index="afterBalance" title="账户余额(元)" />
                    </a-table>

                    <pagination v-show="transactionFormTotal > 0" :total="transactionFormTotal"
                        v-model:page="transactionForm.pn" v-model:limit="transactionForm.ps"
                        @pagination="getTransactionList" />
                </div>
            </a-tab-pane>
            <a-tab-pane key="2" tab="订单记录">
                <div class="page-search-form mb-24">
                    <a-range-picker v-model:value="orderForm.date" :show-time="{ format: 'HH:mm' }"
                        format="YYYY-MM-DD HH:mm" class="mr-24" @change="queryOrderList" />
                    <a-select ref="select" v-model:value="orderForm.orderType" placeholder="订单类型" allowClear class="mr-24"
                        @change="queryOrderList">
                        <a-select-option value="instance">实例订单</a-select-option>
                        <a-select-option value="storage">存储订单</a-select-option>
                    </a-select>
                    <a-input-search v-model:value="orderForm.id" placeholder="实例ID/订单号"
                        style="width: 240px;margin-left: auto;" @search="queryOrderList" />
                </div>

                <div class="page-content">
                    <a-table :dataSource="orderList" :pagination="false" :loading="orderListLoading">
                        <a-table-column key="orderId" data-index="orderId" title="订单号" />
                        <a-table-column key="createdAt" data-index="createdAt" title="创建时间" />
                        <a-table-column key="instanceId" data-index="instanceId" title="实例ID">
                            <template #default="{ record }">
                                {{ record.instanceId || '-' }}
                            </template>
                        </a-table-column>
                        <a-table-column key="subject" data-index="subject" title="订单类型" />
                        <a-table-column key="payStatus" data-index="payStatus" title="状态">
                            <template #default="{ record }">
                                {{ selectDictLabel(orderStatusEnum, record?.payStatus) }}
                            </template>
                        </a-table-column>
                        <a-table-column key="originAmount" data-index="originAmount" title="总价(元)">
                            <template #default="{ record }">
                                {{ parseFloat(record.originAmount).toFixed(2)}}
                            </template>
                        </a-table-column>
                        <a-table-column key="balanceAmount" data-index="balanceAmount" title="实际支付(元)" />
                        <a-table-column key="action" title="操作">
                            <template #default="{ record }">
                                <a-button type="link" @click="geDetail(record.orderId)" style="padding-left:0;">查看详情</a-button>
                            </template>
                        </a-table-column>
                    </a-table>

                    <pagination v-show="orderFormTotal > 0" :total="orderFormTotal" v-model:page="orderForm.pn"
                        v-model:limit="orderForm.ps" @pagination="getOrderList" />
                </div>
            </a-tab-pane>
            <a-tab-pane key="3" tab="账单明细">
                <div class="page-search-form mb-24">
                    <a-date-picker v-model:value="billForm.billDate" picker="month" class="mr-24" @change="queryBillList"
                        :allowClear="false" />
                    <a-select ref="select" v-model:value="billForm.productType" placeholder="所有产品" allowClear class="mr-24"
                        @change="queryBillList" style="width: 200px">
                        <a-select-option value="1">实例存储</a-select-option>
                        <a-select-option value="2">网盘存储</a-select-option>
                        <a-select-option value="3">云服务器（按量计费）</a-select-option>
                        <a-select-option value="4">云服务器（预付费）</a-select-option>
                        <a-select-option value="5">镜像存储</a-select-option>
                    </a-select>
                    <div style="margin-left: auto;">
                        <a-button type="primary" @click="downFile" style="margin-right: 16px;">下载账单</a-button>
                        <a-input-search v-model:value="billForm.id" placeholder="实例ID/订单号" style="width: 200px;"
                            @search="queryBillList" />
                    </div>
                </div>

                <div class="page-content">
                    <a-table :dataSource="billList" :pagination="false" :loading="billListLoading" :scroll="{ x: 2000 }">
                        <a-table-column key="billDate" title="账期" data-index="billDate">
                            <template #default="{ record }">
                                {{ dayjs(billForm.billDate).format('YYYY-MM') }}
                            </template>
                        </a-table-column>
                        <a-table-column key="subject" title="产品" data-index="subject" />
                        <a-table-column key="payType" title="付费方式" data-index="payType">
                            <template #default="{ record }">
                                {{ record.payType == 1 ? '按量付费' : '预付费' }}
                            </template>
                        </a-table-column>
                        <a-table-column key="orderId" title="订单号" data-index="orderId" />
                        <a-table-column key="instanceId" title="实例ID" data-index="instanceId">
                            <template #default="{ record }">
                                {{ record.instanceId || '-' }}
                            </template>
                        </a-table-column>
                        <a-table-column key="createdAt" title="消费时间" data-index="createdAt" />
                        <a-table-column key="gpuNum" title="用量" data-index="gpuNum">
                            <template #default="{ record }">
                                {{ formatUsed(record) }}
                            </template>
                        </a-table-column>
                        <a-table-column key="price" title="价格(元)" data-index="price" />
                        <a-table-column key="originAmount" title="原价(元)" data-index="originAmount">
                            <template #default="{ record }">
                                {{ parseFloat(record.originAmount).toFixed(2) }}
                            </template>
                        </a-table-column>
                        <a-table-column key="payAmount" title="应付金额(元)" data-index="payAmount">
                            <template #default="{ record }">
                                {{ parseFloat(record.payAmount).toFixed(2) }}
                            </template>
                        </a-table-column>
                        <a-table-column key="voucherAmount" title="代金券抵扣(元)" data-index="voucherAmount" />
                        <a-table-column key="balanceAmount" title="余额支付(元)" data-index="balanceAmount" />
                    </a-table>

                    <pagination v-show="billFormTotal > 0" :total="billFormTotal" v-model:page="billForm.pn"
                        v-model:limit="billForm.ps" @pagination="getBillList" />
                </div>

            </a-tab-pane>
            <a-tab-pane key="4" tab="月度账单">
                <div class="page-search-form mb-24">
                    <a-date-picker v-model:value="monthBillForm.BillDate" :disabled-date="disabledDate" picker="month"
                        @change="getMonthBill" :allowClear="false" />
                </div>

                <div class="page-content">
                    <!-- 产品分类汇总 -->
                    <a-table :dataSource="monthBillList.productBillList" :loading="monthBillListLoading">
                        <a-table-column key="month" title="账期" data-index="month">
                            <template #default="{ record }">
                                {{ monthBillList.month }}
                            </template>
                        </a-table-column>
                        <a-table-column key="subject" title="产品" data-index="subject">
                            <template #default="{ record }">
                                {{ selectDictLabel(billStatusEnum, record.subject) }}
                            </template>
                        </a-table-column>
                        <a-table-column key="totalOriginAmount" title="原价(元)" data-index="totalOriginAmount">
                            <template #default="{ record }">
                                {{ parseFloat(record.totalOriginAmount).toFixed(2) }}
                            </template>
                        </a-table-column>
                        <a-table-column key="totalDiscountAmount" title="优惠金额(元)" data-index="totalDiscountAmount" />
                        <a-table-column key="totalPayAmount" title="应付金额(元)" data-index="totalPayAmount">
                            <template #default="{ record }">
                                {{ parseFloat(record.totalPayAmount).toFixed(2) }}
                            </template>
                        </a-table-column>
                        <a-table-column key="totalVoucherAmount" title="优惠券抵扣(元)" data-index="totalVoucherAmount" />
                        <a-table-column key="totalBalanceAmount" title="账户余额支付(元)" data-index="totalBalanceAmount" />

                        <template #summary>
                            <a-table-summary-row>
                                <a-table-summary-cell>合计</a-table-summary-cell>
                                <a-table-summary-cell></a-table-summary-cell>
                                <a-table-summary-cell>
                                    <a-typography-text>{{ monthBillList.totalOriginAmount }}</a-typography-text>
                                </a-table-summary-cell>
                                <a-table-summary-cell>
                                    <a-typography-text>{{ monthBillList.totalDiscountAmount }}</a-typography-text>
                                </a-table-summary-cell>
                                <a-table-summary-cell>
                                    <a-typography-text>{{ monthBillList.totalPayAmount }}</a-typography-text>
                                </a-table-summary-cell>
                                <a-table-summary-cell>
                                    <a-typography-text>{{ monthBillList.totalVoucherAmount }}</a-typography-text>
                                </a-table-summary-cell>
                                <a-table-summary-cell>
                                    <a-typography-text>{{ monthBillList.totalBalanceAmount }}</a-typography-text>
                                </a-table-summary-cell>
                            </a-table-summary-row>
                        </template>
                    </a-table>

                </div>
            </a-tab-pane>
        </a-tabs>

    </section>
</template>

<script setup name="CostDetail">
import { ref } from 'vue'
import { getTransactionListApi, getOrderListApi, getBillListApi, getBillDateApi } from 'api/modules/api.cost'
import dayjs from 'dayjs';
import { selectDictLabel, download, printSize, dateLong } from '@/libs/util.common'
import Pagination from '@/components/common/Pagination.vue'


import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute();

const orderStatusEnum = [
    {
        label: '支付中',
        value: '1'
    },
    {
        label: '支付成功',
        value: '2'
    },
    {
        label: '支付成功',
        value: '3',
    },
    {
        label: '已退款',
        value: '4',
    }
]

// 账单类型
const billStatusEnum = [
    {
        label: '云服务器',
        value: 'instance'
    },
    {
        label: '实例存储',
        value: 'instance_storage'
    },
    {
        label: '网盘存储',
        value: 'net_disk'
    }
]

const activeKey = ref('1')
activeKey.value = route.query.type || '1'

// 获取收支明细
const transactionForm = ref({
    pn: 1,
    ps: 10,
    date: []
})
const transactionFormTotal = ref(0)
const transactionListLoading = ref(false)
const transactionList = ref([])
const getTransactionList = () => {
    const params = {
        startTime: transactionForm.value?.date[0] ? dayjs(transactionForm.value?.date[0]).format('YYYY-MM-DD HH:mm') : '',
        endTime: transactionForm.value?.date[1] ? dayjs(transactionForm.value?.date[1]).format('YYYY-MM-DD HH:mm') : '',
        ...transactionForm.value
    }
    transactionListLoading.value = true
    getTransactionListApi(params).then(res => {
        transactionListLoading.value = false
        transactionFormTotal.value = res.data.total
        transactionList.value = res.data.list
    })
};

getTransactionList()

function queryTransactionList() {
    transactionForm.value.pn = 1
    getTransactionList()
}

// 获取订单记录
const orderForm = ref({
    pn: 1,
    ps: 10,
    date: []
})
const orderFormTotal = ref(0)
const orderListLoading = ref(false)
const orderList = ref([])
const getOrderList = () => {
    const params = {
        startTime: orderForm.value?.date[0] ? dayjs(orderForm.value?.date[0]).format('YYYY-MM-DD HH:mm') : '',
        endTime: orderForm.value?.date[1] ? dayjs(orderForm.value?.date[1]).format('YYYY-MM-DD HH:mm') : '',
        ...orderForm.value
    }
    orderListLoading.value = true
    getOrderListApi(params).then(res => {
        orderListLoading.value = false
        orderFormTotal.value = res.data.total
        orderList.value = res.data.list
    })
};

getOrderList()

function queryOrderList() {
    orderForm.value.pn = 1
    getOrderList()
}

// 获取账单明细
const billForm = ref({
    pn: 1,
    ps: 10,
    billDate: dayjs()
})
const billFormTotal = ref(0)
const billListLoading = ref(false)
const billList = ref([])
const getBillList = () => {
    const params = {
        ...billForm.value,
        billDate: dayjs(billForm.value.billDate).format('YYYY-MM') || ''
    }
    billListLoading.value = true
    getBillListApi(params).then(res => {
        billListLoading.value = false
        billFormTotal.value = res.data.total
        billList.value = res.data.list
    })
}

getBillList()

function queryBillList() {
    billForm.value.pn = 1
    getBillList()
}

// 获取月度账单
const monthBillForm = ref({
    BillDate: dayjs().add(-1, 'month')
})

const disabledDate = current => {
    return current && current > dayjs().add(-1, 'month').endOf('day');
};

const monthBillListLoading = ref(false)
const monthBillList = ref([])
const getMonthBill = (value, dateString) => {
    const billDate = dayjs(monthBillForm.value.BillDate).format('YYYY-MM')
    monthBillListLoading.value = true
    getBillDateApi(dateString || billDate).then(res => {
        monthBillListLoading.value = false
        monthBillList.value = res.data.bill
    })
}

getMonthBill()

// 订单详情
const geDetail = (orderId) => {
    router.push({ path: '/orderDetail', query: { orderId } })
}

// 导出账单
const downFile = () => {
    const billDate = dayjs(billForm.value.billDate).format('YYYY-MM')
    const params = {
        ...billForm.value,
        isExport: true,
        billDate: billDate
    }
    download('/api/v1/cost/bill/list', params, '账单明细')
}

//  格式化用量展示
function formatUsed(record) {
    let formatStr = ''
    if (record.orderType == 'storage') {
        formatStr = printSize(record.byteSize)
    } else {
        formatStr = dateLong(record.startTime, record.closeTime)
        // console.log(str)

    }

    return formatStr
}

</script>

<style scoped lang="scss">
.page-container-list {
    background: #fff;
    min-height: 100%;
    padding: 24px;
}

.page-search-form {
    display: flex;
}

.page-footer {
    background: #fff;
    margin-top: 16px;
    text-align: right;
}
</style>
